package com.keio.common.codec;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.keio.common.protocol.ProxyMessage;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.util.CharsetUtil;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.util.HashMap;
import java.util.List;

/**
 * @author KEIO  on 2022/1/14.
 * @version 1.0
 */
public class ProxyMessageEncoder extends MessageToByteEncoder<ProxyMessage> {

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, ProxyMessage proxyMessage, ByteBuf byteBuf) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(baos);

        int type = proxyMessage.getType();
        dos.writeInt(type);

        JSONObject metaJson = new JSONObject(proxyMessage.getMetaData());
        byte[] metaJsonBytes = metaJson.toString().getBytes(CharsetUtil.UTF_8);
        dos.writeInt(metaJsonBytes.length);
        dos.write(metaJsonBytes);


        dos.write(proxyMessage.getData());

        byte[] data = baos.toByteArray();
        byteBuf.writeInt(data.length);
        byteBuf.writeBytes(data);




    }
}
